# Copyright (c) 2008-2009 Mikhail Chernov 
#
# This file is part of dcExplorer.
#
# dcExplorer is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 2 of the License, or
# (at your option) any later version.
#
# dcExplorer is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with dcExplorer.  If not, see <http://www.gnu.org/licenses/>.

package dcExplorer::wxui::App;
use strict;
use wxui::frame::Main;
use Wx;
use base 'Wx::App';
use Accounts;
use Settings;
use Wx qw(wxID_OK);
use Error::Simple;

sub InitializeAccounts
{
	my $message = undef;
	
	$message = "Data path \"".$Settings::DataPath."\" doesn't exist." unless (-d $Settings::DataPath);
	$message = "Application database \"".$Settings::DataPath."dnc.db\" doesn't exist." unless (-e $Settings::DataPath."dnc.db");
	$message = "XML data directory \"".$Settings::DataPath."xml/\" doesn't exist." unless (-d $Settings::DataPath."xml");

	if ($message)
	{
		Wx::MessageDialog->new(undef, $message." That shouldn't happen under normal operation. Please fix this and run dcExplorer again.", "Data directory error!")->ShowModal;
      return undef;
	}

	my $accounts = dcExplorer::Accounts->new("SQLite:dbname=".$Settings::DataPath."dnc.db");
	my @names = $accounts->names();
	return $accounts if (scalar @names);
	my $credentials = dcExplorer::wxui::dialog::Credentials->new(undef);
	while ($credentials->ShowModal() == wxID_OK)
	{
		try
		{
			my $name = $accounts->Add($credentials->GetUsername(), $credentials->GetPassword());
			$accounts->account($name)->download(["all", "known_planets"]);
			Wx::MessageDialog->new(undef, 
				"Congratulations. Your first account \"".$name."\" was successfully added to the database of the dcExplorer.\n".
				"Feel free to use Account->New menu item to add more accounts to the dcExplorer's database.", 
				"Account added")->ShowModal;
			return $accounts;
		}
		catch Error::Simple with
		{
			my $error = shift;
			Wx::MessageDialog->new(undef, "$error", "Unable to log in!")->ShowModal();
		};
	}
	Wx::MessageDialog->new(undef, "Client is not usable without accounts!", "Unable to log in!")->ShowModal();
	return undef;
}

sub OnInit 
{
	my $accounts = InitializeAccounts();
	if ($accounts)
	{ 
		my $frame = dcExplorer::wxui::frame::Main->new($accounts);
		$frame->Show(1);
	}
	return 1;
}

1;
